package java19_3_24_lambda;

import java19_3_24_lambda.reflect.Student;

import java.lang.reflect.Constructor;
import java.util.Arrays;

/**
 * @author yuisama
 * @date 2022/03/24 18:48
 **/
public class ReflectTest {
    public static void main(String[] args) throws Exception{
//        // 要获取Student类的class对象
//        // 1.直接通过类名称.class
//        Class cls1 = Student.class;
//        // 2.通过Student类的任意一个实例化对象，调用getClass方法
//        Class cls2 = new Student().getClass();
//        // 3.通过Class的forName方法
//        // 此处要传入类的全名称 : 包名.类名
//        Class cls3 = Class.forName("java19_3_24_lambda.reflect.Student");
//        System.out.println(cls1 == cls2);
//        System.out.println(cls3 == cls2);
//        // per编译期和运行时都是Person类型
//        Person per = new Person();
//        // per1编译期是Person类型，运行时就变成了Student类型
//        Person per1 = new Student();
//        System.out.println(per.getClass());
//        System.out.println(per1.getClass());
        // 1.先获取该类的class对象
        Class<Student> cls = Student.class;
//        // 2.调用class对象的newInstance方法产生Student类的实例
//        // 默认调用该类的无参构造
//        Student stu = cls.newInstance();
//        System.out.println(stu);
        // 2.想通过其他构造方法来产生Student类的实例
        // 拿到的是无参构造的constructor对象
//        Constructor constructor = cls.getDeclaredConstructor();
//        // 破坏封装,仅限当前JVM进程中的这个constructor可用
//        constructor.setAccessible(true);
//        Student stu = (Student) constructor.newInstance();
//        Student stu1 = (Student) constructor.newInstance();
//        Constructor constructor1 = cls.getDeclaredConstructor();
//        Student stu2 = (Student) constructor1.newInstance();
//        Student stu3 = new Student();
        // 拿到的是一个参数的constructor对象
        Constructor constructor1 = cls.getDeclaredConstructor(String.class);
        constructor1.setAccessible(true);
        // Student stu = new Student("张三")
        Student stu = (Student) constructor1.newInstance("张三");
        System.out.println(stu);
        // 拿三个参数的有参构造
        Constructor constructor2 = cls.getDeclaredConstructor(String.class,int.class,String.class);
        // Student stu1 = new Student("李四",20,"中国");
        Student stu1 = (Student) constructor2.newInstance("李四",20,"中国");
        System.out.println(stu1);
    }
}